<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\DefaultMedicinal\Services\DefaultMedicinalService;
use App\Modules\Medicinal\Services\MedicinalService;
use Encore\Admin\Layout\Content;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function userIndex(Content $content,Request $request)
    {
        $size = $request->input('size',11);
        $dm_type = $request->input('dm_type','');
        $name = $request->input('name','');
        //设备默认值
        $deviceData = [];
        //查询用户信息
        $field = ['U.id','U.name','U.gender','U.birth_at','U.nickname','U.is_auth','U.from_type','U.phone','U.created_at','A.dm_type','A.dm_age'];
        $userData = DB::table('users as U')->select($field)->leftJoin('archives AS A','U.id','=','A.user_id');
        //条件查询
        if ( isset($_REQUEST['dm_type']) && $dm_type !== '' ) {
            $userData = $userData->where('A.dm_type',$dm_type);
        }
        if ( !empty($name) ) {
            $userData = $userData->where('U.name','like','%'.$name.'%');
        }
        $userData = $userData->orderBy('U.created_at','DESC')->paginate($size);
        //获取用户绑定设备
        if ( !empty($userData) ) {
            $dataList = $userData->toArray()['data'];
            $userIds = array_column($dataList,'id');
            //获取设备
            $deviceData = DB::table('device')->select(['id','device_code','bundled_user_id','bundled_date'])->where('status',1)->whereIn('bundled_user_id',$userIds)->get();
        }
        //渲染视图
        return Admin::content(function (Content $content) use ($userData,$deviceData) {
            $content->body(view("user.user",['result'=>$userData,'device'=>$deviceData]));
        });
    }

    /**
     * 绑定设备列表
     */
    public function deviceIndex(){
        $field = ['D.ID','D.device_code','F.brand_name'];
        $deviceData = DB::table('device AS D')->select($field)->leftJoin('facory AS F','D.facory_id','=','F.id')->where('D.is_bundled',0)->where('D.status',1)->get();
        return response()->success($deviceData);
    }

    /**
     * 用户绑定设备
     */
     public function userBundled(Request $request){
         $code_arr = $request->input('code_arr');
         $id = $request->input('id');
         if ( empty($id) || empty($code_arr) ) return response()->error("PARAM_EMPTY");
         $dataArr = [];
         DB::beginTransaction();
         try{
             //添加数据
             foreach ($code_arr as $key => $value) {
                $update = DB::table('device')->where('device_code',$value)->where('is_bundled',0)->where('status',1)->update(['is_bundled'=>1,'bundled_user_id'=>$id,'bundled_date'=>date('Y-m-d H:i:s')]);
                if ( empty($update) ) throw new \Exception('UPDATE_FAILURE');
             }
             DB::commit();
         }catch (\Exception $e){
             DB::rollBack();
             return response()->error("UPDATE_FAILURE");
         }
         return response()->success();
     }

    /**
     * 基础档案
     */
    public function userDetails(Request $request){
        $id = $request->input('id');
        if ( empty($id) ) {
            header("Location: /admin/user/index");
        }
        //获取基础档案
        $field = ['U.id','U.name','U.gender','U.birth_at','U.papers_type','U.papers','U.height','U.weight','U.phone','U.created_at','A.dm_type','A.dm_age','A.treatment','A.complication','A.is_smoke','A.is_drink'];
        $userData = DB::table('users as U')->select($field)->leftJoin('archives AS A','U.id','=','A.user_id')->where('U.id',$id)->first();
        //获取并发症（后续修改，直接保存字符串。不做查询）
//        $userData->complications = '';
//        if ( !empty($userData->complication) ) {
//            $complicationIds = explode(',',$userData->complication);
//            $dictionaryData = DB::table('dictionary')->select(['id','value'])->whereIn('id',$complicationIds)->where('status',1)->get();
//            foreach ( $dictionaryData as $key => $value ) {
//                $userData->complications .= $value->value.',';
//            }
//            $userData->complications = trim($userData->complications,',');
//        }
        //获取用户当天注射胰岛素数据
        $insulin = DB::table('insulin')->where('maked_at','>=',date('Y-m-d').' 00:00:00')->where('user_id',$id)->get()->toArray();
        $insulinData = [];
//        $insulin = DB::table('insulin')->where('user_id',$id)->get()->toArray();
        if ( !empty($insulin) ) {
            $insulinArr = array_merge(array_unique(array_column($insulin,'insulin_name_cn')));     //所有的胰岛素 去重（这里可能要做多字段去重[insulin_name_en,insulin_name_cn,insulin_type,insulin_preparation]）
            //遍历胰岛素 分组
            foreach ( $insulinArr as $item ) {
                $itemArr = [];
                $itemArr['insulin'] = $item;
                foreach ( $insulin as $key => $value ) {
                    if ( $value->insulin_name_cn == $item ) {
                        if ( $value->meals == 1 ) {
                            $itemArr['before_breakfast'] = $value->insulin_dosage;
                        }else if( $value->meals == 2 ) {
                            $itemArr['before_lunch'] = $value->insulin_dosage;
                        }else if( $value->meals == 3 ) {
                            $itemArr['before_dinner'] = $value->insulin_dosage;
                        }else if( $value->meals == 4 ) {
                            $itemArr['before_sleep'] = $value->insulin_dosage;
                        }
                    }
                }
                array_push($insulinData,$itemArr);
            }
        }
        //获取所有的药品
        $medicinal = DB::table('medicinal')->select(['id','medicinal_en','medicinal_cn','insulin_type','insulin_preparation'])->where('status',1)->where('tag',1)->get();
        //获取当前用户的默认药品
        $userMedicinal = DB::table('default_medicinal')->select(['id','medicinal_id','default_type'])->where('user_id',$id)->get()->toArray();
        if ( !empty($userMedicinal) ) {
            $userMedicinal = array_column($userMedicinal,'medicinal_id','default_type');
        }
        //渲染视图
        return Admin::content(function (Content $content) use ($userData,$insulinData,$medicinal,$userMedicinal) {
            $content->body(view("user.details",['result'=>$userData,'insulin'=>$insulinData,'medicinal'=>$medicinal,'user_medicinal'=>$userMedicinal]));
        });
    }

    /**
     * 测糖记录
     */
    public function userMeasure(Request $request){
        $id = $request->input('id');
        if ( empty($id) ) {
            header("Location: /admin/user/index");die;
        }
        $size = $request->input('size',13);
        $meals = $request->input('meals',0);
        $state = $request->input('state',0);
        $test_at = $request->input('test_at','');
        $field = ['G.id','G.device_code','G.meals','G.glu','G.diet','G.sport','G.remark','G.test_at','G.state','G.type','F.brand_name'];
        $glucoseData = DB::table('glucose AS G')->select($field)
                    ->leftJoin('device AS D','G.device_code','=','D.device_code')
                    ->leftJoin('facory AS F','D.facory_id','=','F.id')
                    ->where('G.user_id',$id);
        if ( !empty($meals) ) {
            $glucoseData = $glucoseData->where('G.meals',$meals);
        }
        if ( !empty($state) ) {
            $glucoseData = $glucoseData->where('G.state',$state);
        }
        if ( !empty($test_at) ) {
            $testTime = explode('|',$test_at);
            if ( count($testTime) > 1 ) {
                $testTimeStart = $testTime[0].' 00:00:00';
                $testTimeEnd = $testTime[1].' 23:59:59';
            }else{
                $testTimeStart = $testTime[0].' 00:00:00';
                $testTimeEnd = $testTime[0].' 23:59:59';
            }
            $glucoseData = $glucoseData->where('G.test_at','>=',$testTimeStart)->where('G.test_at','<=',$testTimeEnd);
        }
        $glucoseData = $glucoseData->orderBy('G.created_at','desc')->paginate($size);
        //渲染视图
        return Admin::content(function (Content $content) use ($glucoseData) {

            $content->body(view("user.measure",['result'=>$glucoseData]));
        });
    }

    /**
     * 用药记录
     */
    public function userInsulin(Request $request){
        $id = $request->input('id');
        if ( empty($id) ) {
            header("Location: /admin/user/index");die;
        }
        $size = $request->input('size',13);
        $meals = $request->input('meals',0);
        $state = $request->input('state',0);
        $maked_at = $request->input('maked_at','');

        $insulinData = DB::table('insulin')->select(['id','insulin_type','type','insulin_name_cn','insulin_dosage','meals','maked_at'])->where('user_id',$id);
        if ( !empty($meals) ) {
            $insulinData = $insulinData->where('meals',$meals);
        }
        if ( !empty($state) ) {
            $insulinData = $insulinData->where('type',$state);
        }
        if ( !empty($maked_at) ) {
            $testTime = explode('|',$maked_at);
            if ( count($testTime) > 1 ) {
                $testTimeStart = $testTime[0].' 00:00:00';
                $testTimeEnd = $testTime[1].' 23:59:59';
            }else{
                $testTimeStart = $testTime[0].' 00:00:00';
                $testTimeEnd = $testTime[0].' 23:59:59';
            }
            $insulinData = $insulinData->where('maked_at','>=',$testTimeStart)->where('maked_at','<=',$testTimeEnd);
        }
        $insulinData = $insulinData->orderBy('created_at','desc')->paginate($size);
        //渲染视图
        return Admin::content(function (Content $content) use ($insulinData) {
            $content->body(view("user.insulin",['result'=>$insulinData]));
        });
    }

    /**
     * 修改用户默认药品
     */
    public function defaultMedicinal(Request $request){
        $default_type = $request->input('default_type');
        $id = $request->input('id');
        $medicinal_id = $request->input('medicinal_id');
        $defaultTypeArr = ['SARA','BASAL'];     //SARA:速效推荐用药    BASAL:中效推荐用药
        if ( empty($default_type) || !in_array($default_type,$defaultTypeArr) || empty($id) || empty($medicinal_id) ) return response()->error("PARAM_EMPTY");
        $saraArr = ['SHORT_ACTING','RAPID_ACTING'];   //2:SHORT_ACTING            3:RAPID_ACTING
        $basalArr = ['INTERMEDIATE_ACTING','BASAL'];  //4:INTERMEDIATE_ACTING     5:BASAL
        //查找药品数据
        $medicinalGet = MedicinalService::oneMedicinal($medicinal_id);
        if ( empty($medicinalGet) ) return response()->error("PARAM_ERROR");
        if ( $default_type == 'SARA' && !in_array($medicinalGet->insulin_type,$saraArr) ) return response()->error("PARAM_ERROR");
        if ( $default_type == 'BASAL' && !in_array($medicinalGet->insulin_type,$basalArr) ) return response()->error("PARAM_ERROR");
        $param = ['user_id'=>$id,'default_type'=>$default_type,'medicinal_id'=>$medicinal_id];
        //查找
        $defaultMedicinal = DefaultMedicinalService::getDefaultMedicinal($param);
        if ( !empty($defaultMedicinal) ) {
            //存在修改
            $result = DefaultMedicinalService::updateDefaultMedicinal($param);
        }else{
            //不存在添加
            $result = DefaultMedicinalService::addDefaultMedicinal($param);
        }
        if ( empty($result) ) return response()->error("UPDATE_FAILURE");
        return response()->success();
    }

    /**
     * 获取用户基本信息
     */
    public function userInfo(Request $request){
        $user_id = $request->input('user_id');
        if ( empty($user_id) ) return response()->error("PARAM_EMPTY");
        $field = ['id','name','nickname','gender','birth_at','vip_start_at','vip_end_at','status'];
        $userData = DB::table('users')->where('id',$user_id)->select($field)->first();
        if ( empty($userData) ) response()->error("PARAM_ERROR");
        $userData = get_object_vars($userData);
        //获取最新推荐更新时间
        $prescription = DB::table('prescription')->select(['created_at'])->where('user_id',$user_id)->orderBy('created_at','desc')->first();
        $userData['save_time'] = empty($prescription->created_at) ? '' : $prescription->created_at;
        return response()->success($userData);
    }
}
